package com.liuxvru.project.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.liuxvru.common.utils.SecurityUtils;
import com.liuxvru.project.domain.Work;
import com.liuxvru.project.domain.WorkAttachment;
import com.liuxvru.project.mapper.WorkAttachmentMapper;
import com.liuxvru.project.mapper.WorkMapper;
import com.liuxvru.project.service.IWorkAttachmentService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

/**
 * 工作项附件Service业务层处理
 *
 * @author liuxvru
 * @date 2025-02-17
 */
@Service
public class WorkAttachmentServiceImpl extends ServiceImpl<WorkAttachmentMapper, WorkAttachment> implements IWorkAttachmentService {
    @Autowired
    WorkMapper workMapper;
    /**
     * 查询工作项附件列表
     *
     * @param workAttachment 工作项附件
     * @return 工作项附件
     */
    @Override
    public List<WorkAttachment> selectWorkAttachmentList(WorkAttachment workAttachment) {
        return baseMapper.selectWorkAttachmentList(workAttachment);
    }

    @Override
    public int add(WorkAttachment workAttachment, Long workItemId) {
        Long userId = SecurityUtils.getUserId();
        Work work = workMapper.selectById(workItemId);
        workAttachment.setProjectId(work.getProjectId());
        workAttachment.setCreatedBy(userId);
        workAttachment.setUpdatedBy(userId);
        workAttachment.setWorkId(workItemId);
        return baseMapper.insert(workAttachment);
    }

    @Override
    @Transactional
    public int edit(WorkAttachment workAttachment) {
        Long userId = SecurityUtils.getUserId();
        workAttachment.setUpdatedBy(userId);
        return baseMapper.updateById(workAttachment);
    }

    @Override
    @Transactional
    public int delFiles(Long projectId, Long workItemId, List<Long> list) {
        Long userId = SecurityUtils.getUserId();
        List<WorkAttachment> workAttachments = baseMapper.selectList(new LambdaQueryWrapper<WorkAttachment>()
                .eq(WorkAttachment::getProjectId, projectId)
                .eq(WorkAttachment::getWorkId, workItemId)
                .eq(WorkAttachment::getCreatedBy, userId)
                .in(WorkAttachment::getAttachmentId, list));
        if (workAttachments.size() != list.size()) {
            throw new RuntimeException("删除失败");
        }
        return baseMapper.deleteBatchIds(list);
    }

}
